import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../common/api/x_message_assemble_communicate.dart';
import '../../../../common/api/x_organization_assemble_control.dart';
import '../../../../common/models/im/im_conversation.dart';
import '../../../../common/models/orgs/o2_person.dart';
import '../../../../common/utils/debounce.dart';
import '../../../../common/utils/log_util.dart';
import '../../../../common/values/o2.dart';
import 'index.dart';

class ConversationPickerController extends GetxController {
  ConversationPickerController();

  final state = ConversationPickerState();
  final searchController = TextEditingController();
  final _debouncer = Debounce(milliseconds: 300); // 设置防抖时间为300毫秒

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    fetchConversations();
    super.onReady();
  }

  // 输入框变化监听
  void searchInput(String text) {
    _debouncer.run(() {
      _search();
    });
  }

  /// 搜索
  Future<void> _search() async {
    final keyword = searchController.text.trim();
    OLogger.d('搜索内容。。。。$keyword');
    if (keyword.isEmpty) {
      _clearSearchResult();
    } else {
      await searchConversationList(keyword);
      await searchPersonList(keyword);
      state.showSearchResult = true;
    }
  }

  _clearSearchResult() {
    state.showSearchResult = false;
    state.searchConversationList.clear();
    state.searchPersonList.clear();
  }

  Future<void> searchConversationList(String keyword) async {
    state.searchConversationList.clear();
    final list = state.conversationList.toList();
    state.searchConversationList.addAll(list
        .where((element) =>
            element.title?.contains(keyword) == true ||
            (element.personList?.where((p) => p.contains(keyword)) ?? [])
                .isNotEmpty)
        .toList());
  }

  Future<void> searchPersonList(String keyword) async {
    state.searchPersonList.clear();
    var list = await OrganizationControlService.to.personSearch(keyword);
    if (list != null && list.isNotEmpty) {
      state.searchPersonList.addAll(list);
    }
  }

  Future<void> fetchConversations() async {
    var list = await MessageCommunicationService.to.myConversationList();
    if (list != null && list.isNotEmpty) {
      state.conversationList.clear();
      state.conversationList.addAll(list);
    }
  }

  void chooseConversation(IMConversationInfo info) {
    Get.back(result: info);
  }

  void tapPerson(O2Person person) {
    if (person.distinguishedName != null &&
        person.distinguishedName!.isNotEmpty) {
      createConversation(person.distinguishedName!);
    }
  }

  Future<void> createConversation(String person) async {
    final conv = await MessageCommunicationService.to
        .createConversation(O2.imConversationTypeSingle, [person]);
    if (conv != null) {
      chooseConversation(conv);
    }
  }
}
